package com.example.temp.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.temp.common.Constants;
import com.example.temp.common.Result;
import com.example.temp.controller.DAO.SysUserDao;
import com.example.temp.entity.SysUser;
import com.example.temp.service.SysUserService;
import com.example.temp.utils.TokenUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;

@Tag(name = "用户管理")
@RestController
@RequestMapping("/sysuser")
public class SysUserController {

    @Autowired
    private SysUserService  sysUserService;

    /**
     * 用于查找全部的用户信息
     * @return
     */

    @Operation(summary = "列表，用于测试json格式的数据")
    @GetMapping
    public List<SysUser> findList() {
        return sysUserService.list();
    }

    /**
     * 用于翻页
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Operation(summary = "分页")

    @GetMapping("/page")
    public Result Page(@RequestParam @Parameter(description="页数") Integer pageNum,
                               @RequestParam @Parameter(description="页面大小")Integer pageSize,
                               @RequestParam(defaultValue = "") @Parameter(description="loginName模糊查询")String loginName){
        IPage<SysUser>page=new Page<>(pageNum,pageSize);
        QueryWrapper<SysUser>queryWrapper=new QueryWrapper<>();
        queryWrapper.like("login_name",loginName);
        IPage<SysUser>userIPage=sysUserService.page(page,queryWrapper);
        //用于后台访问用户信息
        SysUser currentUser = TokenUtils.getCurrentUser();
        System.out.println("<----------当前用户信息---------->"+currentUser.getLoginName());

        return Result.success(userIPage);
    }

    /**
     * 用于添加用户信息
     * @param sysUser
     * @return
     */
    @PostMapping
    @Operation(summary = "添加用户信息")
    public Result save(@RequestBody  SysUser sysUser){
        return Result.success(sysUserService.saveUser(sysUser));
    }

    /**
     * 用于删除指定单个用户
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    @Operation(summary = "删除指定单个用户")
    public Result delete(@PathVariable Integer id) {
        return Result.success(sysUserService.removeById(id));
    }

    /**
     * 用于批量删除
     * @param ids
     * @return
     */
    @PostMapping("/del/batch")
    @Operation(summary = "用于批量删除")
    public Result deleteBatch(@RequestBody List<Integer> ids) {
        return Result.success(sysUserService.removeBatchByIds(ids));
    }


    /**
     * 根据登录名查找用户昵称
     * @param loginName
     * @return
     */
    @GetMapping("/username/{loginName}")
    @Operation(summary = "根据登录名查找用户昵称")
    public Result findOne(@PathVariable String loginName) {
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("login_name",loginName);
        return Result.success(sysUserService.getOne(queryWrapper));
    }


    /**
     * 导出用户信息
     * @param response
     * @throws Exception
     */
    @Operation(summary = "导出用户信息")
    @GetMapping("/export")
    public void export(HttpServletResponse response) throws Exception {
        // 从数据库查询出所有的数据
        List<SysUser> list = sysUserService.list();

        ExcelWriter writer = ExcelUtil.getWriter(true);

        writer.write(list, true);

        // 设置浏览器响应的格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("用户信息", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        out.close();
        writer.close();

    }
    /**
     * excel 导入
     * @param file
     * @throws Exception
     */
    @Operation(summary = "导入用户信息")
    @PostMapping("/import")
    public Boolean imp(MultipartFile file) throws Exception {
        InputStream inputStream = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);

        //@Alias解决英文表头的问题
        List<SysUser> list = reader.readAll(SysUser.class);
        System.out.println(list);
        sysUserService.saveBatch(list);

        return true;
    }

    @Operation(summary = "用于登录")
    @PostMapping("/login")
    public Result login(@RequestBody SysUserDao sysUserDao) {

        String username = sysUserDao.getLoginName();
        String password = sysUserDao.getPassword();

        if (StrUtil.isBlank(username) || StrUtil.isBlank(password)) {
            return Result.error(Constants.CODE_400,"参数错误");
        }

        SysUserDao dao=sysUserService.login(sysUserDao);
        return Result.success(dao);

    }


    @Operation(summary = "用于注册----打算删了")
    @PostMapping("/register")
    public Result Register(@RequestBody SysUserDao sysUserDao) {
        String loginName = sysUserDao.getLoginName();
        String password = sysUserDao.getPassword();
        if (StrUtil.isBlank(loginName) || StrUtil.isBlank(password)) {
            return Result.error(Constants.CODE_400,"参数错误");
        }
        return Result.success(sysUserService.register(sysUserDao));
    }
}
